﻿using System;
using System.Data.Linq;
using System.Linq;
using CoreLibrary.Paging;
using CoreLibrary.Repo;
using IBBI.DataBase.Obj;
using IBBI.DataBase.Persistent;

namespace IBBI.DataBase.Impl {

    public class EquipmentService : BaseRepository<Equipment>, IEquipmentService{

        private static readonly Func<DataContext, int, Equipment>
           LinqGetEquipmentById = CompiledQuery.Compile((DataContext context, int id) =>
               context.GetTable<Equipment>().SingleOrDefault(o => o.Id == id));

        private static readonly Func<DataContext, int, int, IQueryable<Equipment>>
           LinqGetEquipments = CompiledQuery.Compile((DataContext context, int offset, int limit) =>
               context.GetTable<Equipment>().Skip(offset).Take(limit));

        private static readonly Func<DataContext, int, IQueryable<Equipment>>
           LinqGetEquipmentsByCategory = CompiledQuery.Compile((DataContext context, int category) =>
               context.GetTable<Equipment>().Where(e => e.CategoryId == category));

        public void RemoveEquipment(int equipmentId) {
            Execute((context, ts) => {
                var equipment = LinqGetEquipmentById(context, equipmentId);
                context.GetTable<Equipment>().DeleteOnSubmit(equipment);
                context.SubmitChanges();
                ts.Complete();
            });
        }

        public void AddEquipment(Equipment equipment) {
            Execute((context, ts) => {
                context.GetTable<Equipment>().InsertOnSubmit(equipment);
                context.SubmitChanges();
                ts.Complete();
            });
        }

        public void UpdateEquipment(UpdateEquipmentRequest request) {
            throw new NotImplementedException();
        }

        public PagingResult<Equipment> ListEquipments(PagingRequest request) {
            return Execute(context => {
                var equipments = context.GetTable<Equipment>().ToList();
                return new PagingResult<Equipment> {
                    Offset = request.Offset,
                    Total  = equipments.Count,
                    Data   = equipments.Skip(request.Offset).Take(request.Limit).ToList(),
                };
            });
        }

        public PagingResult<Equipment> ListEquipmentsByCategory(int category, PagingRequest request) {
            return Execute(context => {
                var equipments = LinqGetEquipmentsByCategory(context, category).ToList();
                return new PagingResult<Equipment> {
                    Offset = request.Offset,
                    Total  = equipments.Count,
                    Data   = equipments.Skip(request.Offset).Take(request.Limit).ToList(),
                };
            });
        }
    }

}